﻿
namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;

    public class JsonFacetRangesParser : ISolrResponseParser<string, IDictionary<string, FacetRange>>
    {
        public IDictionary<string, FacetRange> Parse(string result)
        {
            if (result == null)
            {
                return null;
            }

            IDictionary<string, FacetRange> facetRangesResult = null;
            var bytes = Encoding.UTF8.GetBytes(result);

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max))
            {
                var xmlDoc = XDocument.Load(reader);

                var facetCounts = xmlDoc.Root.Element("facet_counts");

                if (facetCounts == null)
                {
                    return null;
                }

                var facetRanges = facetCounts.Element("facet_ranges");

                if (facetRanges == null)
                {
                    return null;
                }

                facetRangesResult = new Dictionary<string, FacetRange>(facetRanges.Elements().Count());

                foreach (var element in facetRanges.Elements())
                {
                    var fieldName = element.Name.LocalName;

                    if (!facetRangesResult.ContainsKey(fieldName))
                    {
                        facetRangesResult.Add(fieldName, new FacetRange() { Start = element.Element("start").Value, End = element.Element("end").Value, Gap = element.Element("gap").Value });
                    }

                    var countsElement = element.Element("counts");

                    if (countsElement != null)
                    {
                        facetRangesResult[fieldName].Counts = new List<FacetField>(countsElement.Elements().Count());

                        var i = 0;

                        foreach (var countElement in countsElement.Elements())
                        {
                            if ((i % 2) == 0)
                            {
                                facetRangesResult[fieldName].Counts.Add(new FacetField() { Name = countElement.Value });
                            }
                            else
                            {
                                facetRangesResult[fieldName].Counts[i >> 1].Count = int.Parse(countElement.Value);
                            }

                            i++;
                        }
                    }
                }
            }

            return facetRangesResult;
        }
    }
}
